package top.infopub.util;


import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;



/**
 * 校验工具类
 * @author Awoke
 * @version 2018年9月14日
 * @see ValidateUtils
 * @since
 */
public final class ValidateUtils {

    private static Pattern mobile_validator = Pattern.compile("^[1][3,4,5,6,7,8,9][0-9]{9}$");

    /**
     * 手机号码
     * @param str
     * @return 
     * @see
     */
    public static boolean isMobile(String str) {
        Matcher m = mobile_validator.matcher(str);
        return m.matches();
    }

    /**
     * 判断是否为数字
     * 
     * @param str
     * @return
     */
    public static boolean isNumberAndInteger(String str) {
        Pattern pattern = Pattern.compile("^\\d+$|^\\d+\\.\\d+$|-\\d+$");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    
    /**
     * 校验营业执照-社会统一信用编码（18位）
     * 
     * @param license
     * @return
     */
	public static boolean isValidLicense18(String license) {
		if (StringUtils.isEmpty(license)) {
			return false;
		}
		if (license.length() != 18) {
			return false;
		}

		String regex = "^([159Y]{1})([1239]{1})([0-9ABCDEFGHJKLMNPQRTUWXY]{6})([0-9ABCDEFGHJKLMNPQRTUWXY]{9})([0-90-9ABCDEFGHJKLMNPQRTUWXY])$";
		if (!license.matches(regex)) {
			return false;
		}

		String baseCode = "0123456789ABCDEFGHJKLMNPQRTUWXY";
		char[] baseCodeArray = baseCode.toCharArray();
		Map<Character, Integer> codes = new HashMap<Character, Integer>();
		for (int i = 0; i < baseCode.length(); i++) {
			codes.put(baseCodeArray[i], i);
		}
		char[] businessCodeArray = license.toCharArray();
		Character check = businessCodeArray[17];
		if (baseCode.indexOf(check) == -1) {
			return false;
		}
		int[] wi = { 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28 };
		int sum = 0;
		for (int i = 0; i < 17; i++) {
			Character key = businessCodeArray[i];
			if (baseCode.indexOf(key) == -1) {
				return false;
			}
			sum += (codes.get(key) * wi[i]);
		}
		int value = 31 - sum % 31;
		return value == codes.get(check);
	}
    
    /**
     * 校验密码格式
     * 6-18位数字或字母
     * 
     * @param pw
     * @return
     */
    public static boolean isValidPassword(String pw) {
         Pattern pattern = Pattern.compile("^[a-zA-Z\\d]{6,18}$");
         Matcher matcher = pattern.matcher(pw);
         return matcher.matches();
    }
}
